package leetcode_core.leetcode_4;

import java.util.Stack;

/**
 * 功能描述
 *
 * @author: 张庭杰
 * @date: 2022年11月05日 16:16
 */
public class ParseBoolExpr {
    public boolean parseBoolExpr(String expression) {
        Stack<Character> stack = new Stack<>();
        int len = expression.length();
        for(int i = 0;i<len;i++){
            char c = expression.charAt(i);
            if(c == ','){
                continue;
            }else if(c != ')'){
                stack.push(c);
            }else{
                int t = 0;int f = 0;
                while (stack.peek() != '('){
                    Character bool = stack.pop();
                    if(bool == 't'){
                        t++;
                    }else if( bool == 'f'){
                        f++;
                    }
                }
                Character sign = stack.pop();
                if(sign == '!'){
                    stack.push(f == 1?'t':'f');
                }else if(sign == '&'){
                    stack.push(f >= 1?'f':'t');
                }else if(sign == '|'){
                    stack.push(t >= 1?'t':'f');
                }
            }
        }
        return stack.pop() == 't';
    }
}
